package com.demo.stack;

public class ArrayStackTest {
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(5);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        System.out.println(stack.pop());
        stack.showStack();
    }
}

/**
 * 使用数据来模拟栈，先进后出
 */
class ArrayStack{
    private Integer maxSize;

    /**
     * 栈顶，初始值为-1
     */
    private Integer top = -1;

    private Integer[] stack;

    public ArrayStack(Integer maxSize) {
        this.maxSize = maxSize;
        stack = new Integer[maxSize];
    }

    /**
     * 判断栈是否已满
     * @return
     */
    public boolean isFull() {
        return top == maxSize - 1;
    }

    /**
     * 判断栈是否为空
     * @return
     */
    public boolean isEmpty() {
        return top == -1;
    }

    /**
     * 数据入栈
     * @param value
     */
    public void push(Integer value) {
        if (isFull()) {
            throw new RuntimeException("栈已满");
        }
        top++;
        stack[top] = value;
    }

    /**
     * 数据出栈（从栈顶到栈底，先进后出）
     * @return
     */
    public Integer pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈空");
        }
        Integer value = stack[top];
        top--;
        return value;
    }

    /**
     * 遍历栈，查看栈中有哪些元素
     */
    public void showStack() {
        if (isEmpty()) {
            throw new RuntimeException("栈空");
        }
        for (int i = top; i >= 0; i--) {
            System.out.printf("%d -> %d \r\n", i, stack[i]);
        }
    }
}
